package com.kantboot.db.common.runtool;

import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.experimental.Accessors;
import util.PasswordUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 不一网络科技社统一数据库生成器
 */
@Data
@Accessors(chain = true)
public class KantbootDBGenerator {
    public static void main(String[] args) {
        new KantbootDBGenerator()
                .setDbName("asads121s")
                .setPassword("12345678").generator();
// user_id user_exsss_id
    }

    private List<String> sqlList;
    /**
     * 地址加端口（默认为`localhost:3306`）
     */
    private String address = "localhost:3306";

    /**
     * 数据库名称
     */
    private String dbName ;

    /**
     * 用户名（默认为`root`）
     */
    private String username = "root";

    /**
     * 密码
     */
    private String password;

    public KantbootDBGenerator(){
        sqlList=new ArrayList<String>();

        sqlList.add("CREATE TABLE `ces_kantboot_file` (\n" +
                "  `id` bigint NOT NULL AUTO_INCREMENT,\n" +
                "  `path` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '文件路径',\n" +
                "  `type_str` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '文件类型',\n" +
                "  `is_delete` int DEFAULT '0' COMMENT '逻辑删除（0 未删除，1 已删除）',\n" +
                "  `gmt_create` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\n" +
                "  `gmt_modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后一次修改时间',\n" +
                "  PRIMARY KEY (`id`) USING BTREE\n" +
                ") ENGINE=InnoDB AUTO_INCREMENT=253 DEFAULT CHARSET=utf8mb3;");

        sqlList.add("CREATE TABLE `ces_kantboot_user` (\n" +
                "  `id` bigint NOT NULL AUTO_INCREMENT,\n" +
                "  `nickname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '昵称',\n" +
                "  `gender` int DEFAULT NULL COMMENT '性别',\n" +
                "  `realname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '真实姓名',\n" +
                "  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `salt` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `authz` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `avatar_url` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `phone_number` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `id_card` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `vip_lv` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `balance` bigint DEFAULT '0',\n" +
                "  `is_delete` int DEFAULT '0',\n" +
                "  `gmt_create` datetime DEFAULT CURRENT_TIMESTAMP,\n" +
                "  `gmt_modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n" +
                "  `total_revenue` bigint DEFAULT '0' COMMENT '总收入',\n" +
                "  PRIMARY KEY (`id`) USING BTREE\n" +
                ") ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb3");

        sqlList.add("CREATE TABLE `ces_kantboot_wechat_user` (\n" +
                "  `id` bigint NOT NULL AUTO_INCREMENT,\n" +
                "  `user_id` bigint DEFAULT NULL,\n" +
                "  `openid` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `unionid` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `avatar_url` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `country` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `gender` int DEFAULT NULL,\n" +
                "  `nickname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `province` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,\n" +
                "  `gmt_create` datetime DEFAULT CURRENT_TIMESTAMP,\n" +
                "  `gmt_modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n" +
                "  `is_delete` int DEFAULT '0',\n" +
                "  PRIMARY KEY (`id`) USING BTREE\n" +
                ") ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb3");

    }

    @SneakyThrows
    public void generator(){
        Class.forName("com.mysql.cj.jdbc.Driver");

        String url="jdbc:mysql://"
                +this.address+"/"
                +this.dbName+
                "?useSSL=false" +
                "&autoReconnect=true" +
                "&useUnicode=true" +
                "&characterEncoding=utf-8" +
                "&serverTimezone=Asia/Shanghai";
        Connection conn = null;
        try{
            conn = DriverManager.getConnection(url, this.username, this.password);
        }catch(SQLNonTransientConnectionException e){
            //当数据库不存在时自动创建
            System.out.println("===发现没有"+this.dbName+"数据库===");
            System.out.println("---正在创建"+this.dbName+"数据库");
            createDatabase();
            System.out.println("---已完成"+this.dbName+"数据库的创建");
            conn = DriverManager.getConnection(url, this.username, this.password);
        }

        Statement stat = conn.createStatement();

        for (String sql : this.sqlList) {
            try {
                System.out.println("===正在创建数据库表===");
                stat.executeUpdate(sql);
            }catch (SQLSyntaxErrorException e){
                System.err.println(e.toString());
            }
        }
        System.out.println("===数据库表创建完成===");

        Scanner scanner = new Scanner(System.in);
        System.out.println("设置管理账号：");
        String adminUsername=scanner.nextLine();
        System.out.println("设置管理员密码：");
        String adminPassword=scanner.nextLine();
        System.out.println("设置管理员昵称：");
        String adminNickname=scanner.nextLine();
        System.out.println("设置管理员性别（0 代表女，1 代表男，2 代表保密，3 代表男变女{也可直接选择0}，4 代表女变男{请不要在公元2024年之前使用}）：");
        Integer adminGender=scanner.nextInt();


        //生成盐值
        String salt= UUID.randomUUID().toString();

        String adminPasswordMD5 = PasswordUtil.toMd5(adminPassword, salt);
        String adminSettingSql=
                "INSERT INTO ces_kantboot_user(`username`,`password`,`salt`,`nickname`,`gender`)" +
                        " VALUES('"+adminUsername+"','"+adminPasswordMD5+"','"+salt+
                        "','"+adminNickname+"',"+adminGender+")";
        stat.executeUpdate(adminSettingSql);
        System.out.println("管理账户生成成功");
        System.out.println("账号：\t"+adminUsername);
        System.out.println("密码：\t"+adminPassword);
    }

    /**
     * 创建数据库
     */
    @SneakyThrows
    public void createDatabase(){
        Class.forName("com.mysql.cj.jdbc.Driver");

        String url="jdbc:mysql://"
                +this.address+"/sys"+
                "?useSSL=false" +
                "&autoReconnect=true" +
                "&useUnicode=true" +
                "&characterEncoding=utf-8" +
                "&serverTimezone=Asia/Shanghai";

        Connection conn = DriverManager.getConnection(url,
                this.username, this.password);

        Statement stat = conn.createStatement();

        //创建表test
        stat.executeUpdate("CREATE DATABASE "+this.dbName);

        conn.close();
        stat.close();
    }

}
